<template>
  <div v-loading="loading">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="dataForm"
    >

      <!--文件-->
      <FileTable file-title="归档附件信息" :list.sync="form.archivedFileList" data-type="oa_seal_archived" :business-id="businessId" @uploadBeforeTable="uploadBeforeTable" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <!--      <FormBtn ref="formBtn" :bus-data="form" has-permi="oa:seal" :btn-hide="btnHide" :menu-key="menuKey" />-->
      <!--      <save-btn :cancel-func="cancel" />-->
      <save-btn has-permi="oa:seal" />
    </div>
  </div>
</template>

<script>
  import { saveOaSealArchivedFile, getOaSeal, deleteOaSealDetail } from '@/api/oa/seal/oaSeal'
  import { findDealLimit } from '@/api/base/deal/dealBase'
  import { findFundFof } from '@/api/fund/fundBase'

  export default {
    components: {
    },
    data() {
      return {
        // 菜单标识
        menuKey: 'oa_seal',
        // 是否隐藏保存按钮
        btnHide: false,
        // 是否隐藏其它按钮
        otherBtnHide: false,
        loading: false,
        // 表单参数
        form: {
          fileList: [],
          archivedFileList: []
        },
        // 表单校验
        title: undefined,
        rules: {
          applyUserId: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
          applyTime: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
          usineTypeOne: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
          usineTypeTwo: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
          actTitle: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
          otherType: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }]
        },
        // 操作按钮默认不展示
        buttonShow: true,
        // 校验用印明细不能为空
        oaSealDetailListRules: {
          investMainType: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
          investMain: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
          sealType: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }]
        },
        dataType: 'oa_seal',
        uploaderOpen: false,
        // 合同下拉
        selectDropDownContract: [],
        // 合同下拉,用印类型一级
        oaSealOneTypeDict: [],
        usineTypeOneOption: [],
        // 用印二级类型
        usineTypeTwoOption: [],
        sealTypeDict: undefined,
        contractMessage: this.$t('请选择付款类型后获取合同'),
        contractPageLoading: false,
        selectDropDownContractTempCount: 0,
        yesNoOptions: [],
        businessId: undefined,
        fundDataList: [],
        dealDataList: [],
        selectLoading: false
      }
    },
    watch: {
      'form.usineTypeOne': {
        handler(val) {
          if (val) {
            this.getDicts('seal_usine_type_' + val).then(response => {
              this.usineTypeTwoOption = response.data
            })
          }
        },
        deep: true,
        immediate: true
      }
    },
    mounted() {
      this.$bus.$emit('async_done')
    },
    created() {
      this.getDicts('seal_type').then(response => {
        this.sealTypeDict = response.data
      })
      this.getDicts('seal_usine_type').then(response => {
        this.oaSealOneTypeDict = response.data
      })
      this.getDicts('sys_yes_no').then(response => {
        this.yesNoOptions = response.data
      })
      this.findListData()
    },
    methods: {
      // 初始化数据
      init(data) {
        this.selectDropDownContractTempCount = 0
        this.contractMessage = this.$t('请选择付款类型后获取合同')
        if (data != null && data !== '' && data.id !== undefined) {
          this.loading = true
          getOaSeal(data.id).then(response => {
            this.form = response.data
            this.remoteMethodDeal()
            this.loading = false
          })
        } else {
          this.loading = false
          this.reset()
        }
      },
      schange(val, name) {
        console.log(name, val)
        this.form.contractAssociated = undefined
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          applyUserId: this.$store.state.user.userId,
          applyTime: new Date(),
          usineTypeOne: undefined,
          usineTypeTwo: undefined,
          otherType: undefined,
          fileCount: undefined,
          sealRidingSeam: undefined,
          contractAssociated: undefined,
          projectOrFund: undefined,
          sealType: undefined,
          source: undefined,
          remark: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          fileList: [],
          delFlag: undefined
        }
        this.resetForm('form')
      },
      // 取消按钮
      cancel() {
        if (this.$parent.$parent.uploadFormOpen !== undefined) {
          this.$parent.$parent.uploadFormOpen = false
        }
        if (this.$parent.$parent.reset !== undefined) {
          this.$parent.$parent.reset()
        }
      },
      // 关闭form页面
      closeForm() {
        // 关闭form页面遮罩层
        this.loading = false
        // 关闭form页面
        if (this.$parent.$parent.uploadFormOpen !== undefined) {
          this.$parent.$parent.uploadFormOpen = false
        }
        // 刷新list页面
        if (this.$parent.$parent.getList !== undefined) {
          this.$parent.$parent.getList()
        }
      },
      /** 提交按钮 */
      submitForm: function(type) {
        return new Promise((resolve, reject) => {
          var temp = this.form.oaSealDetailList
          if (temp === null || temp === undefined || temp === '' || temp <= 0) {
            this.msgError(this.$t('至少添加一条用印明细'))
          } else {
            this.$refs['form'].validate(valid => {
              // 验证数据
              if (valid) {
                // 弹出遮罩层
                this.loading = true
                // 保存数据
                saveOaSealArchivedFile(this.form).then(response => {
                  if (response.code === 200) {
                    // 点击的按钮是保存并启动流程
                    if (type === 'process') {
                      // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                      this.form.id = response.data
                      // 启动流程
                      this.startProcess(response.data)
                      // 点击的仅保存
                    } else {
                      this.msgSuccess(this.$t('保存成功'))
                      // 关闭form页面
                      this.closeForm()
                    }
                    resolve()
                  } else {
                    this.msgError(response.msg)
                    this.loading = false
                    reject()
                  }
                }).catch(() => {
                  this.loading = false
                })
              } else {
                this.locationError(document)
                reject()
              }
            })
          }
        })
      },
      // 启动流程
      startProcess: function(dataId) {
        this.loading = false
        // 启动流程时候传入的参数
        const processData = {}
        // 待办标题
        processData.title = this.form.actTitle
        // 业务表名
        processData.dataTable = 'oa_seal'
        // 业务ID
        processData.dataId = dataId
        // 业务表单地址
        processData.formPath = '@/views/oa/seal/oaSealForm'

        // 业务表单打印地址
        processData.viewPath = '@/views/oa/seal/oaSealView'

        // 菜单标识(根据菜单标识判断的走哪个流程)
        processData.menuKey = this.menuKey
        this.startProcessByMenu(processData, () => {
          this.form.actStatus = 'D'
          this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
          this.closeForm()
        })
      },
      // 用印明细
      addPayment() {
        const row = {
          id: undefined,
          investMainType: '',
          investMain: '',
          sealType: '',
          remark: ''
        }
        if (!(this.form.oaSealDetailList instanceof Array)) {
          this.$set(this.form, 'oaSealDetailList', [])
        }
        this.$nextTick(() => {
          this.form.oaSealDetailList.push(row)
        })
      },
      // 删除用印明细
      delHandle(index, row) {
        // eslint-disable-next-line no-undef
        const id = row.id
        if (id !== undefined && id !== '' && id != null) {
          this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
          })
            .then(function() {
              return deleteOaSealDetail(id)
            }).then(() => {
            this.form.oaSealDetailList.splice(index, 1)
            return this.msgSuccess(this.$t('删除成功'))
          })
            .catch(function() {})
        } else {
          this.form.oaSealDetailList.splice(index, 1)
        }
      },
      // 添加附件
      uploader() {
        this.uploaderOpen = true
        this.title = '上传附件'
      },
      // 获取附件列表
      getData(fileList) {
        this.form.fileList = fileList
      },
      // 删除附件
      delAdjunct(index) {
        this.form.fileList.splice(index, 1)
      },
      //
      usineTypeOneChange(usineTypeOne) {
        this.form.usineTypeTwo = undefined
        this.form.contractAssociated = undefined
        // 基金或项目时 清空OA合同. 日常用印时恢复OA合同
        this.oaSealOneTypeDict.some(item => {
          if (item.dictValue === usineTypeOne) {
            this.form.businessType = usineTypeOne
            if (usineTypeOne === 'deal') {
              this.selectDropDownContract = []
              this.contractMessage = this.$t('请先选择项目,加载相应合同')
            } else {
              this.contractMessage = this.$t('请选择合同')
              this.selectDropDownContract = this.selectDropDownContractTemp
            }
            if (usineTypeOne === 'deal' || usineTypeOne === 'fund') {
              this.rules.projectOrFund = [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
            } else {
              this.rules.projectOrFund = []
            }
          }
        })
      },
      viewContractPage(id) {
        var proArr = this.selectDropDownContract
        if (proArr !== null && proArr !== undefined && proArr !== '') {
          proArr.forEach(item => {
            if (id === item.id) {
              if (item.actId === undefined) {
                id = item.rows.actId
              } else {
                id = item.actId
              }
            }
          })
        }
        if (id !== null && id !== '' && id !== undefined) {
          console.log(id)
          this.contractPageLoading = true
          this.$nextTick(() => {
            var proData = {}
            proData.actId = id
            this.$refs.processInfoForm.init(proData)
          })
        } else {
          this.msgError(this.$t('请先选择一个合同!'))
        }
      },
      uploadBeforeTable(callback) {
        this.businessId = undefined
        if (this.isEmpty(this.form.projectOrFund)) {
          this.businessId = undefined
          callback()
        } else {
          if (this.form.projectOrFund.length === 1) {
            this.businessId = this.form.projectOrFund[0]
            callback()
          } else {
            var that = this
            const h = this.$createElement
            var map = []
            this.form.projectOrFund.forEach(item => {
              this.dealDataList.forEach(dict => {
                if (dict.id === item) {
                  map.push({ id: dict.id, name: dict.dealName })
                }
              })
              this.fundDataList.forEach(dict => {
                if (dict.id === item) {
                  map.push({ id: dict.id, name: dict.fundName })
                }
              })
            })
            this.$msgbox({
              title: this.$t('请选择') + this.form.usineTypeOne === 'fund' ? this.$t('基金') : this.$t('项目'),
              message: h('el-select',
                { props: { value: that.businessId, filterable: true },
                  ref: 'selectView',
                  style: { width: '100%' },
                  on: {
                    change: e => {
                      console.log('12change', e)
                      that.businessId = e
                      that.$refs.selectView.value = e
                    }
                  }
                },
                [
                  map.map(it => {
                    return h('el-option', {
                      props: { label: it.name, key: it.id, value: it.id }
                    })
                  })
                ]
              ),
              showCancelButton: true,
              closeOnClickModal: false,
              confirmButtonText: this.$t('确定'),
              cancelButtonText: this.$t('取消'),
              beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                  if (that.businessId) {
                    done()
                  } else {
                    this.$message.warning(this.$t('请先选择'))
                  }
                } else {
                  done()
                }
              }
            }).then(() => {
              console.log(that.businessId)
              callback()
            }).catch(() => {
            })
          }
        }
      },
      remoteMethodDeal(query) {
        this.selectLoading = true
        const queryDeal = {
          pageSize: 30,
          pageNum: 1,
          dealIdList: (this.form.projectOrFund !== Array) ? (this.isEmpty(this.form.projectOrFund) ? [] : this.form.projectOrFund) : (this.form.projectOrFund.filter(i => i && i.trim())),
          dealName: query,
          scopeAuthority: true
        }
        findDealLimit(queryDeal).then(response => {
          this.dealDataList = (response.rows === null ? [] : response.rows)
          this.selectLoading = false
        }).catch(() => {
          this.selectLoading = false
        })
      },
      findListData() {
        findFundFof({ scope: this.scopeAuthority }).then(response => {
          this.fundDataList = response.data
        })
      }

    }
  }
</script>
